package server;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 自定义ClassLoader
 */
public class MyClassLoader extends ClassLoader {
    // 文件目录
    private String classDir;

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String realPath = classDir + name.replace(".", "/") + ".class";
        byte[] classBytes = null;
        Path path = null;

        try {
            path = Paths.get(new URI(realPath));
            classBytes = Files.readAllBytes(path);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Class<?> aClass = defineClass(name, classBytes, 0, classBytes.length);
        return aClass;
    }

    public MyClassLoader(String classDir) {
        this.classDir = "file://".concat(classDir);
    }
}
